import os
import time
import datetime
from PyQt5.QtCore import QThread, pyqtSignal


class NewTaskThread(QThread):
    success = pyqtSignal(int, str)
    error = pyqtSignal(int, str)

    def __init__(self, sku_id, current_row_count, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.sku_id = sku_id
        self.row_count = current_row_count

    def run(self):
        print("线程自动执行", self.sku_id, self.row_count)

        # 1.根据商品ID获取详细信息：标题
        from jd import v1
        try:
            title = v1.get_title(self.sku_id)
            if title:
                self.success.emit(self.row_count, title)
                return
            self.error.emit(self.row_count, "获取标题失败")
        except Exception as e:
            self.error.emit(self.row_count, "获取标题失败")


class TaskThread(QThread):
    success_signal = pyqtSignal(int)
    error_signal = pyqtSignal(int, str)
    stop_signal = pyqtSignal(int)

    def __init__(self, sku_id, price, scheduler, current_row_count, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.sku_id = sku_id
        self.price = float(price)
        self.scheduler = scheduler
        self.row_index = current_row_count

    def run(self):
        from jd import v1

        while True:
            try:
                # 1.如果人为停止
                if self.scheduler.terminate:
                    self.stop_signal.emit(self.row_index)  # 更新表格
                    self.scheduler.destroy_thread(self)  # 任务列表摘除此线程
                    self.exec_log("人为停止")  # 记录日志
                    return

                # 2.获取最新价格
                new_price = v1.get_price(self.sku_id)
                if not new_price:
                    # 错误，表格更新
                    self.error_signal.emit(self.row_index, "请求异常，未获取到价格")
                    # 将自己从thread_list中摘除
                    self.scheduler.destroy_thread(self)
                    # 日志
                    self.exec_log("请求异常，未获取到价格")
                    return

                if new_price <= self.price:
                    # 成功，表格更新
                    self.success_signal.emit(self.row_index)

                    # 自己线程从thread_list中摘除
                    self.scheduler.destroy_thread(self)

                    # 发送邮件通知（调用上一节的邮件代码）

                    # 记录运行日志
                    self.exec_log("获取成功")

                    return

                self.exec_log("最新价格{}".format(new_price))

                time.sleep(3)

            except Exception as e:
                self.exec_log("请求异常，详细异常：{}".format(str(e)))
                self.error_signal.emit(self.row_index, str(e))
                self.scheduler.destroy_thread(self)
                return

    def exec_log(self, message):
        log_file_path = os.path.join('log', "{}.log".format(self.sku_id))

        with open(log_file_path, mode='a', encoding='utf-8') as f:
            date_string = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            f.write("{}-{}\n".format(date_string, message))


class StopThread(QThread):
    update_signal = pyqtSignal(str)

    def __init__(self, scheduler, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.scheduler = scheduler

    def run(self):
        while True:
            time.sleep(1)
            running_count = len(self.scheduler.thread_list)
            self.update_signal.emit("停止中（{}）".format(running_count))
            if running_count == 0:
                break

        self.update_signal.emit("已终止")
